package com.jnevision.menu.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jnevision.menu.mapper.MenuMapper;
import com.jnevision.menu.model.Menu;

/**
 * <p>
 * 菜单 服务实现类
 * </p>
 *
 * @author gavin
 * @since 2019-07-13
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> {

    @Autowired
    private MenuMapper menuMapper;
    private List<Menu> menuList = new ArrayList<>();

    public List<Integer> getMenu(int roleId) {
        return this.menuMapper.getMenu(roleId);
    }

    private void loopChildren(int id) {
        List<Menu> children = this.baseMapper.selectList(new QueryWrapper<Menu>().eq("parent_id", id));

        if (!CollectionUtils.isEmpty(children)) {
            this.menuList.addAll(children);
            for (Menu menu : children) {
                this.loopChildren(menu.getId());
            }
        }
    }

    public List<Menu> getChildren(int id) {
        this.menuList.clear();
        this.menuList.add(this.getById(id)); // 放入本身部门

        this.loopChildren(id); // 放入所管辖的部门
        return this.menuList;
    }
}
